/*
 *  TAOCHELE.COM
 *  2013.4.4
 *  LIZHE
 */
$(document).ready(function() {
	
	$(document).ajaxStart(function(){
		$("#ajax_loading").show();
	});
	$(document).ajaxComplete(function(){
		$("#ajax_loading").fadeOut();
	});
	
    //切换城市
    $('#change_city').modal({
        backdrop: true,
        keyboard: true,
        show: false
    });
    $('#successful').modal({
        backdrop: true,
        keyboard: false,
        show: true
    });
    $('a').tooltip({
        animation: false,
        placement: 'bottom',
        trigger: 'hover'
    });
    $('.icon-gift').tooltip({
        animation: false,
        placement: 'bottom',
        title: '二手车按揭服务',
        trigger: 'hover'
    });
    //车型 URL跳转
	$("#select_brand").change(function(){
		var url = this[this.selectedIndex].value;
		window.open(url, "_self");
	});
	$("#select_model").change(function(){
		var url = this[this.selectedIndex].value;
		window.open(url, "_self");
	});
	//搜索
	$("#buy_search").click(function(){
		var query = encodeURI($("#query").val());
		var s_url = $("#search_url").val();
		if (query != ""){
			window.open(s_url+query, "_self");	
		}
	});
	
	$('input[name="is_pic"],input[name="on_sale"]').click(function(){
		var url_t = $(this).attr('url_t');
		var url_f = $(this).attr('url_f');
		if(this.checked == true){
			window.open(url_t, "_self");
		}else{
			window.open(url_f, "_self");
		}
	});
	
	//选择车辆 弹出工具框
	$('input[name="check_car"]').click(function(){
		var id = $(this).val();
		var num = $('#select_num').text();
		if(this.checked == true){
			$("#t_"+id).addClass("table-checked");
			open_box();
			num++;
		}else{
			$("#t_"+id).removeClass("table-checked");
			num--;
		}
		$('#select_num').text(num);
	});
	
	
	
	$(window).resize(function() {
		//窗口大小调整事件
		
		//profit 浮动 位置
		setProfitwidth();
	});
	
	try{
		setProfitwidth();
		var top = $('.profit').offset().top - 50;
		$('.profit').affix({offset: {top: top}});
		
		setPricenavwidth();
	}catch(err){
	   
	}
	//$('.profit').affix();
	var run = 1;
	var profitrun = 1;
	$(window).scroll(function() {
		//滚动条事件
		
		
		//回到顶部
		var scrollHeight = parseInt(document.body.getBoundingClientRect().top);
		if (scrollHeight < -500) {
			$('.back_top').fadeIn();
		} else {
			$('.back_top').fadeOut();
		}
		
		
		try{
			//底部 价格FIXED
			var img_top = $(".img_view").offset().top - ($(window).scrollTop());
			var price_navtop = $(".price_nav_top").offset().top - ($(window).scrollTop());
			var nowHeight = $(window).height() - $(".price_nav").height();
			//alert(price_navtop);
			if ((img_top < -10) && (price_navtop > nowHeight)){
				$(".price_nav").css("position",'fixed');
			}else{
				$(".price_nav").css("position",'relative');
			}
		}catch(err){
			   
		}
		
		
		try{
			//加载简略配置信息
			var nowHeight = $(window).height() - $(".price_nav").height();
			if (($("#pz").offset().top - ($(window).scrollTop())) < nowHeight){
				
				if(run == 1){
					var name_id = $('#name_id').val();
					$.post("/ajax/getdetail",{name_id:name_id},function(result){   
				    	$('#detail_arr').html(result);   
					});
					run++;
				}
			}
		}catch(err){
			   
		}
		
		
		try {
			//页面载入RProfit
			var nowHeight = $(window).height() - $("#bprofit_div").height();
			if (($("#bprofit_div").offset().top - ($(window).scrollTop())) < nowHeight){
				if(profitrun == 1){
					getBProfit();
					profitrun++;
				}
			}
		} catch (err) {
		}


	});
	
	//BUY底部所有车源展示
	//$('#foot_autos a:first').tab('show');
    $('#foot_autos a').mouseover(function (e) {
        e.preventDefault();
        $(this).tab('show');
    });
	
    
    //显示TEL AJAX
    $('.tel-number').one("click",function() {
    	var cid = $('#cid').val();
		$.post("/ajax/getmoblie",{cid:cid},function(result){     
        	$('.tel-number label').text(result);  
        	$('.tel-number').addClass("tel-number-lv");   
		});
    });
    
    //大图点击 下一张
    $('.img_view img').click(function(){
    	var next_id = $(this).attr('id');
    	next_id = "aimg_" + (parseFloat(next_id.replace(/aimg_/,"")) + parseFloat(1));
    	scrollTo(next_id);
    });
    
    
    //切换城市
    $("#c_city").one("click",function(){
    	$.post("/ajax/getallcity",{},function(result){     
        	$('#city_arr').html(result);   
    	});
    });
    

    //打开弹出窗口
	$("a[id='showWindow']").click(function(){
		var data = $(this).attr('data');
		showWindow(data);
	});



	//页面载入时显示验证码
	$("a[id='captcha'] img").after(function(){
		getCaptcha();
	});
	
	//ie支持PLACEHOLDER
	$("input[type='text']").placeholder();
	$("textarea").placeholder();
	

	//批量收藏
	$("#addFavorites").click(function(){
		var ids = "";
	    $("input[name='check_car']").each(function(){
	        if(this.checked == true) {
	            if (ids == "") {
	                ids = this.value;
	            } else {
	                ids = ids + "," + this.value;
	            }
	        }
	    });
	    if (!ids) {
	    	errorMsg('请选择需要收藏的车辆！');
	    }else{
	    	addFavorite(ids);
	    }
	});
	
	//页面载入RProfit
	$("#rprofit_div").after(function(){
		getRProfit();
	});
	$("#eprofit_div").after(function(){
		getEProfit();
	});
	
	
	//浏览记录
	$("#showHistory").one("click",function(){
		var wHeight = $(window).height();
		var count = Math.round(wHeight / 34);
		$.post("/ajax/gethistory",{count:count},function(result){  
			$('#History').html(result);
		});
	});
	
	//页面载入后 记录历史和点击数
	$(".buy_view").after(function(){
		setHistory();
		//CLICK
		setViews();
	});
	
});


//点击数
function setViews(){
	var cid = $('#cid').val();
	$.post("/ajax/setviews",{cid:cid},function(result){  
	});
}

//VIEW AJAX浏览记录
function setHistory(){
	var title = $('.buy_view h3').text();
	var cid = $('#cid').val();
	$.post("/ajax/sethistory",{cid:cid, title:title},function(result){  
	});
}

//清除浏览记录
function clearHistory(){
	$.post("/ajax/clearhistory",{},function(result){  
		$('#History').html("<small>您的浏览记录空空如也</small>");
	});
}

//底部PROFIT  ERROR时用
function getEProfit(){
	var count = 30;
	var city_id = $('input[name=city_id]').val();
	$('#eprofit_div').html('<div><img src="/img/loading.gif" /><small>  正在加载数据...</small><br /><br /></div>');
	$.post("/ajax/getrprofit",{city_id:city_id, count:count},function(result){  
		$('#eprofit_div').html(result);
	});
}

//底部PROFIT
function getBProfit(){
	var count = 6;
	var city_id = $('input[name=city_id]').val();
	$('#bprofit_div').html('<div><img src="/img/loading.gif" /><small>  正在加载数据...</small><br /><br /></div>');
	$.post("/ajax/getrprofit",{city_id:city_id, count:count},function(result){  
		$('#bprofit_div').html(result);
	});
}

//右侧取PROFIT
function getRProfit(){
	var wHeight = $(window).height();
	var count = Math.round(wHeight / 120);
	if (count%2 == 1){
		count = count++;
	}
	var city_id = $('input[name=city_id]').val();
	$('#rprofit_div').html('<div><img src="/img/loading.gif" /><small>  正在加载数据...</small><br /><br /></div>');
	$.post("/ajax/getrprofit",{city_id:city_id, count:count},function(result){  
		$('#rprofit_div').html(result);
	});
}

function addFavorite(ids){
	var ref = $('input[name=ref]').val();
	//收藏示例
	$.post("/ajax/addfavorite",{ids: ids},function(result){  
		if (result == 1){
			successMsg("您已成功收藏该信息！", ref);
		}else{
			errorMsg(result);
		}
		
	});

}



//刷新验证码
function getCaptcha(){
	$('#captcha').html('<img src="/img/loading.gif" />'); 
	$.post("/ajax/getcaptcha",{},function(result){  
		$('#captcha').html(result);
    	//$('#captcha img').attr('src', '/data/tmp/captcha/' + result);
	});
}


//SHOWWINDOW 调用
function showWindow(data){
	$("#dialog").html("<center class=\"loading\"><i></i></center>");
	$("#dialog").load(data);
	$("#dialog").modal('show'); 
	return true;
}

function scrollTo(go){
    //# 平滑滚动 a=#
    var targetOffset = $("#" + go).offset().top - 50;
    $('html,body').animate({
        scrollTop: targetOffset
    },800);
}

function back_top(){
	$("html,body").animate({scrollTop: 0}, 800);
}

//price_nav 浮动宽
function setPricenavwidth(){
	var width = $('.span9').width();
	$('.price_nav').css('width', width);
}

//PROFIT 浮动宽设定
function setProfitwidth(){
	var width = $('.all_right').width();
	$('.profit').css('width', width);
}

//打开
function open_box(){
	$('.buy_box').fadeIn();
}
function close_box(){
	$('.buy_box').fadeOut();
}
function empty_box(){
    $("input[name='check_car']").each(function(){
        if(this.checked == true) {
        	var id = $(this).val();
        	this.checked = false;
        	$("#t_"+id).removeClass("table-checked");
        	$('#select_num').text('0');
        	close_box();
        }
    });
}

//对比车辆
function contrast(){
	var ids = "";
	var is = 0;
    $("input[name='check_car']").each(function(){
        if(this.checked == true) {
            if (ids == "") {
                ids = this.value;
            } else {
                ids = ids + "," + this.value;
                is++;
            }
        }
    });
    if (is == 0) {
    	errorMsg('请至少选择2辆车进行对比');
    }else if(is >= 5){
    	errorMsg('最多5辆车同时进行对比');
    }else{
    	var url = '/buy/contrast/cids/' + ids;
    	window.open(url, "_blank");
    }

}
//$('#myModal').modal(options);

//ERROR 对话框
function errorMsg(res){
	$("#errorMsg p").html(res);
    $('#errorMsg').modal({
        backdrop: true,
        keyboard: true,
        show: true
    });
}

//操作成功 对话框
function successMsg(res,url){
	var data = "/dialog/success/?res=" + encodeURI(res) + "&url=" + encodeURIComponent(url);
	showWindow(data);
}
